package oss

import (
	"encoding/json"
	"fmt"
	"gitee.com/slclub/aliyun-oss/conf"
	"gitee.com/slclub/aliyun-oss/logq"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

type StatementClass struct {
	Effect   string
	Action   []string // ["oss:PutObject"]
	Resource []string // ["acs:oss:*:*:"acs:oss:*:*:slclub-dev/testdir", "acs:oss:*:*:slclub-dev/testdir/*""]
	//Condition interface{}
	//Principal []string
}

type Policy struct {
	Version   string // "1"
	Statement []StatementClass
}

// 角色授权信息
type RoleRAM struct {
	RoleArn         string
	RoleSessionName string
	Policy          Policy
}

type PolicyMgr struct {
}

func (pm *PolicyMgr) GetRequestClient() (*oss.Client, error) {
	client, err := oss.New(conf.Config.OSS.UploadEndPoint, conf.Config.OSS.AccessKeyId, conf.Config.OSS.AccessKeySecret)
	if err != nil {
		logq.Error("RAM REQUEST ", "Unvalid access key or secret")
		return nil, err
	}
	return client, err
}

// PutBucketPolicy
func (pm *PolicyMgr) PutBucketPolicy(bucket string, policy *Policy) error {
	client, err := pm.GetRequestClient()
	if err != nil {
		logq.Error("RAM REQUEST ", "Unvalid access key or secret")
		return err
	}
	policy_json, _ := json.Marshal(policy)
	err = client.SetBucketPolicy(bucket, string(policy_json))
	if err != nil {
		logq.Error(":", err)
		return err
	}
	fmt.Println("SetBucketPolicy success")
	return nil
}

// 利用json串 设置policy
func (pm *PolicyMgr) PutPolicyWithJson(bucket string, json_data []byte) error {
	//policy := Policy{}

	//return pm.PutBucketPolicy(bucket, policy)
	client, err := pm.GetRequestClient()
	if err != nil {
		logq.Error("RAM REQUEST ", "Unvalid access key or secret")
		return err
	}
	err = client.SetBucketPolicy(bucket, string(json_data))
	if err != nil {
		logq.Error(":", err)
		return err
	}
	fmt.Println("SetBucketPolicy success")
	return nil
}

func (pm *PolicyMgr) GetBucketPolicy(bucket string) string {
	client, _ := pm.GetRequestClient()
	str, err := client.GetBucketPolicy(bucket)
	if err != nil {
		logq.Error(":", err)
	}
	return str
}

func (pm *PolicyMgr) DeleteBucketPolicy(bucket string) error {
	client, _ := pm.GetRequestClient()
	client.DeleteBucketPolicy(bucket)
	return nil
}
